

from rest_framework import serializers
from users.models import User

class UserModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = [
            'id',
            'username',
            'mobile',
            'email',

            'password' # 补充密码字段
        ]

        extra_kwargs = {
            'password': {'max_length': 20, 'min_length': 8, 'write_only': True}, # 只参与反序列化
            'username': {'max_length': 20, 'min_length': 5},
        }

    def create(self, validated_data):
        # 重写模型类序列化器的create方法，来实现新建User对象密码加密
        validated_data['is_staff'] = True # 默认新建的用户是员工
        user = User.objects.create_user(**validated_data)
        return user